/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ViewPeer.java
 *
 * Created on May 26, 2009, 9:18:47 PM
 */

package cn2;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.*;
import javax.swing.table.*;




/**
 *
 * @author michaellangmayr
 */
public class ViewPeer extends javax.swing.JFrame {
    Overlay myOverlay;
    ArrayList results = new ArrayList();
    RemotePeer downloadPeer;
    

    /** Creates new form ViewPeer1 */
    public ViewPeer(Overlay myOverlay) {
        initComponents();
        this.myOverlay = myOverlay;
        
        this.setTitle("Not Connected: Listening on port " + myOverlay.getListenPort());


        this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        WindowListener windowListener = new WindowAdapter()
        {
            // anonymous WindowAdapter class
            public void windowClosing ( WindowEvent w )
            {
                
                ViewPeer.this.myOverlay.disconnect();

               
                ViewPeer.this.setVisible( false );
                ViewPeer.this.dispose();
                System.exit(0);
                
            } // end windowClosing
        };// end anonymous class

    this.addWindowListener( windowListener );
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")


    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();
        jButton4 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setForeground(java.awt.Color.black);

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Suche");

        jButton1.setText("Download");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Filename", "Peer", "Filesize", "MD5"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jTable1);

        jButton2.setText("Suche");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Filename", "Peer"
            }
        ));
        jScrollPane1.setViewportView(jTable2);

        jButton3.setText("Pause");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton5.setText("Connect");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton4.setText("Show Neighbours");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel2.setForeground(java.awt.Color.green);
        jLabel2.setText("Ready");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(951, Short.MAX_VALUE)
                        .add(jButton5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 126, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(jButton1)
                            .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 568, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(135, 135, 135)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                        .add(org.jdesktop.layout.GroupLayout.LEADING, jProgressBar1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE))
                                    .add(org.jdesktop.layout.GroupLayout.LEADING, jButton3))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 10, Short.MAX_VALUE))
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                .add(322, 322, 322)
                                .add(jButton4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 167, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                    .add(layout.createSequentialGroup()
                        .add(29, 29, 29)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 125, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(layout.createSequentialGroup()
                                .add(jLabel1)
                                .add(18, 18, 18)
                                .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 296, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(41, 41, 41)
                                .add(jButton2)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jButton5)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 9, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1)
                    .add(jButton2))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jLabel2)
                .add(42, 42, 42)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 83, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(3, 3, 3)
                        .add(jProgressBar1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jButton3))
                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 239, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton4)
                    .add(jButton1)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        jLabel2.setText("Searching...");
        jLabel2.setForeground(java.awt.Color.RED);
        SearchTask search = new SearchTask(myOverlay, this, jTextField1.getText());
        search.execute();

        
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        jLabel2.setText("Searching...");
        jLabel2.setForeground(java.awt.Color.RED);
        SearchTask search = new SearchTask(myOverlay, this, jTextField1.getText());
        search.execute();
    }//GEN-LAST:event_jTextField1ActionPerformed

    // Connect Button
    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
         try{
             if(myOverlay.getOwnNeighbours().size() < 1) {

                myOverlay.Connect();
                myOverlay.PrintNeighbours();

                // Set Buttontext to disconnect when connected
                jButton5.setText("Disconnect");
                this.setTitle("Connected: Listening on port " + myOverlay.getListenPort());
             } else {
                 myOverlay.disconnect();

                 // Set Buttontext to disconnect when connected
                 jButton5.setText("Connect");
                 this.setTitle("Not Connected: Listening on port " + myOverlay.getListenPort());
             }


         } catch(Exception e) {
             System.out.println("[ViewPeer] Unable to Connect to " + myOverlay.rp.toString());
         }
    }//GEN-LAST:event_jButton5ActionPerformed

    // Download Button
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Vector v = (Vector)((DefaultTableModel)jTable1.getModel()).getDataVector().get(jTable1.getSelectedRow());
        String filename = (String)v.get(0);
        String peerString = (String)v.get(1);
        String md5 = (String)v.get(3);

        ArrayList peers = new ArrayList();
        String[] tmp = peerString.split(",");
        for(int k = 1; k < tmp.length; k++) {
            String peerIP = tmp[k].split(":")[0];
            int peerPort = Integer.parseInt(tmp[k].split(":")[1]);

            RemotePeer tmpPeer = new RemotePeer(peerIP, peerPort);
            peers.add(tmpPeer);
        
        }

        long filesize = Long.parseLong((String)v.get(2));

        // Write Download in Download Table
        String[] headers = {"Filename", "Peer", "Status"};
        DefaultTableModel dtm = new DefaultTableModel(headers, 0);

        String[] data = { filename, peerString.toString()};
        dtm.addRow(data);

        jTable2.setModel(dtm);

        
        // Start Download
        jProgressBar1.setMinimum(0);
        jProgressBar1.setMaximum((int)filesize);
        jProgressBar1.setStringPainted(true);
        jProgressBar1.setString(null);
        
        //myOverlay.download(filename, new RemotePeer(peerIP, peerPort), filesize, (long)0, jProgressBar1);

        

        DownloadTask task = new DownloadTask(myOverlay, filename, peers, filesize, jProgressBar1, this, md5);
        //task.addPropertyChangeListener(this);
        task.execute();

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        if(downloadPeer.isPause() == false) {
            downloadPeer.togglePause();
            jProgressBar1.setString("Paused");
            
        }

    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        myOverlay.PrintNeighbours();
    }//GEN-LAST:event_jButton4ActionPerformed

    public void search(ArrayList results) {
        //this.results = myOverlay.searchFileNeighbours(jTextField1.getText());
        this.results = results;


        // Create new Table Model
        String[] headers = {"Filename", "Peer", "Filesize", "MD5"};
        Vector headers1 = new Vector();
        headers1.add(headers[0]);
        headers1.add(headers[1]);
        headers1.add(headers[2]);
        headers1.add(headers[3]);
        DefaultTableModel dtm = new DefaultTableModel(headers, 0);


        Vector data = new Vector();
        

        // Read Arraylist into Array for Table
        Iterator it = this.results.iterator();
        while(it.hasNext()){


            Vector dataRow = new Vector();
            SearchResult sr = ((SearchResult)it.next());
            int indexX = -1;
            boolean duplicate = false;

            for(int j=0; j< data.size(); j++) {
                if(((Vector)data.elementAt(j)).contains(sr.getHash())) {
                    indexX = j;
                }
                if(((String)((Vector)data.elementAt(j)).elementAt(1)).contains(sr.getRemotePeer().getIP() + ":" + sr.getRemotePeer().getPort()) && ((Vector)data.elementAt(j)).contains(sr.getHash())) {
                   duplicate = true;
                }
                if(sr.getRemotePeer().getIP().equals(myOverlay.getLocalAddress()) && sr.getRemotePeer().getPort() == myOverlay.getListenPort()) {
                    duplicate = true;
                }
            }
            if(indexX != -1 && duplicate == false) {
                Vector tmp = new Vector();
                tmp = (Vector)data.elementAt(indexX);
                tmp.set(1, tmp.elementAt(1) + "," + sr.getRemotePeer().toString());
                System.out.println("[ViewPeer] Summarizing a duplicate");

            } else if(duplicate == false) {

                //String[] dataRow = { sr.getFilename(), sr.getRemotePeer().toString(), Long.toString(sr.getFilesize()), "" };

                dataRow.add(sr.getFilename());
                dataRow.add(sr.getRemotePeer().toString());
                dataRow.add(Long.toString(sr.getFilesize()));
                dataRow.add(sr.getHash());

                data.add(dataRow);

                System.out.println(sr.getFilename() + sr.getRemotePeer().toString());
            }

        }

        // Add Rows to Search Results Table
        for(int k = 0; k < data.size(); k++) {
            Vector tmp = new Vector();
            tmp = (Vector)data.elementAt(k);
            int no = ((String)tmp.elementAt(1)).split(",").length;
            tmp.set(1, "(" + no + ")," + (String)tmp.elementAt(1));
            dtm.addRow((Vector)data.elementAt(k));
        }

        jTable1.setModel(dtm);
        jLabel2.setText("Ready");
        jLabel2.setForeground(java.awt.Color.GREEN);
    }





    /**
    * @param args the command line arguments
    */
    public static void main(String args[], final Overlay ov) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ViewPeer(ov).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

}
